#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-12-7
# software: PyCharm

from sqlalchemy.orm import sessionmaker
from.models import Message
from sqlalchemy import create_engine
import traceback

# 配置数据库连接，根据实际情况修改连接字符串
engine = create_engine('mysql+pymysql://root:12345678@localhost/message_board')
Session = sessionmaker(bind=engine)

# 插入留言信息
def insert_message(msg_content, msg_author, review_status):
    try:
        session = Session()
        new_message = Message(msg_content=msg_content, msg_author=msg_author, review_status=review_status)
        session.add(new_message)
        session.commit()
        session.close()
        print("留言信息插入成功")
    except Exception as e:
        print(f"插入留言信息出错: {e}")
        print(traceback.format_exc())

# 根据留言ID删除留言信息
def delete_message(msg_id):
    try:
        session = Session()
        message = session.query(Message).filter(Message.msg_id == msg_id).first()
        if message:
            session.delete(message)
            session.commit()
            print("留言信息删除成功")
        else:
            print(f"未找到ID为 {msg_id} 的留言信息，无法删除")
        session.close()
    except Exception as e:
        print(f"删除留言信息出错: {e}")
        print(traceback.format_exc())

# 根据留言ID更新留言内容（可按需扩展更新其他字段）
def update_message(msg_id, new_content):
    try:
        session = Session()
        message = session.query(Message).filter(Message.msg_id == msg_id).first()
        if message:
            message.msg_content = new_content
            session.commit()
            print("留言信息更新成功")
        else:
            print(f"未找到ID为 {msg_id} 的留言信息，无法更新")
        session.close()
    except Exception as e:
        print(f"更新留言信息出错: {e}")
        print(traceback.format_exc())

# 查询所有留言信息
def query_messages():
    try:
        session = Session()
        messages = session.query(Message).all()
        for message in messages:
            print(f"留言ID: {message.msg_id}, 内容: {message.msg_content}, 留言人: {message.msg_author}, "
                  f"审核状态: {message.review_status}, 留言时间: {message.msg_time})")
        session.close()
    except Exception as e:
        print(f"查询留言信息出错: {e}")
        print(traceback.format_exc())
